package com.heima.article.listener;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.heima.article.mapper.ApArticleConfigMapper;
import com.heima.common.constants.WmNewsMessageConstants;
import com.heima.model.article.pojos.ApArticleConfig;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.apache.kafka.clients.consumer.ConsumerRecord;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.kafka.annotation.KafkaListener;
import org.springframework.stereotype.Component;

import java.util.Map;

@Component
@Slf4j
public class KafkaArticleListener {
    @Autowired
    private ApArticleConfigMapper apArticleConfigMapper;

    @KafkaListener(topics = WmNewsMessageConstants.WM_NEWS_UP_OR_DOWN_TOPIC)
    public void downOrUp(ConsumerRecord<String,String> record){
        //1.获取消息内容
        String value = record.value();
        log.info("接收到消息：{}", value);

        //2.解析内容
        //2.1判断内容是否存在
        if (StringUtils.isEmpty(value)){
            return;
        }
        //2.2将内容转为对象
        Map<String,String> map = JSON.parseObject(value, Map.class);

        //3.获取文章id,文章状态
        Long articleId = Long.valueOf(map.get("articleId"));
        Short enable = Short.valueOf(map.get("enable"));
        //4.根据id查询文章在配置表中的信息
        LambdaQueryWrapper<ApArticleConfig> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(ApArticleConfig::getArticleId,articleId);
        ApArticleConfig apArticleConfig = apArticleConfigMapper.selectOne(queryWrapper);
        //5.判断传递的enable参数，修改文章配置信息
        if (apArticleConfig == null){
            return;
        }
        apArticleConfig.setIsDown(enable==0?false:true);

        apArticleConfigMapper.updateById(apArticleConfig);
    }
}
